<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>09_迭代对象-迭代器中断实现</title>
  <!-- 
  
  -->
</head>
<body>

  <script>
    class Person {
      constructor(name, age, friends) {
        this.name = name;
        this.age = age;
        this.friends = friends;
      }

      // 实例方法 自定义类的迭代器
      [Symbol.iterator]() {
        let index = 0;
        let arr = Object.values(this);
        return {
          next: () => {
            if (index < arr.length) {
              return {
                value: arr[index++],
                done: false
              }
            } else {
              return {
                value: undefined,
                done: true
              }
            }
          },
          return: () => {
            console.log('迭代器提前终止了');
            return {
              value: undefined,
              done: true
            }
          }
        }
      }
    }

    const p = new Person('张三', 18, ['李四', '王五']);
    for (const item of p) {
      console.log(item);
      if (item === 18) {
        break;
      }
    }

  </script>
  
</body>
</html>